{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-07T03:07:26.568900Z",
     "start_time": "2020-04-07T03:07:26.285169Z"
    }
   },
   "outputs": [],
   "source": [
    "import cv2  \n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import os \n",
    "from tqdm import tqdm"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Transform Video to .npy Format"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-07T03:07:26.812857Z",
     "start_time": "2020-04-07T03:07:26.805109Z"
    }
   },
   "outputs": [],
   "source": [
    "def getOpticalFlow(video):\n",
    "    \"\"\"Calculate dense optical flow of input video\n",
    "    Args:\n",
    "        video: the input video with shape of [frames,height,width,channel]. dtype=np.array\n",
    "    Returns:\n",
    "        flows_x: the optical flow at x-axis, with the shape of [frames,height,width,channel]\n",
    "        flows_y: the optical flow at y-axis, with the shape of [frames,height,width,channel]\n",
    "    \"\"\"\n",
    "    # initialize the list of optical flows\n",
    "    gray_video = []\n",
    "    for i in range(len(video)):\n",
    "        img = cv2.cvtColor(video[i], cv2.COLOR_RGB2GRAY)\n",
    "        gray_video.append(np.reshape(img,(224,224,1)))\n",
    "\n",
    "    flows = []\n",
    "    for i in range(0,len(video)-1):\n",
    "        # calculate optical flow between each pair of frames\n",
    "        flow = cv2.calcOpticalFlowFarneback(gray_video[i], gray_video[i+1], None, 0.5, 3, 15, 3, 5, 1.2, cv2.OPTFLOW_FARNEBACK_GAUSSIAN)\n",
    "        # subtract the mean in order to eliminate the movement of camera\n",
    "        flow[..., 0] -= np.mean(flow[..., 0])\n",
    "        flow[..., 1] -= np.mean(flow[..., 1])\n",
    "        # normalize each component in optical flow\n",
    "        flow[..., 0] = cv2.normalize(flow[..., 0],None,0,255,cv2.NORM_MINMAX)\n",
    "        flow[..., 1] = cv2.normalize(flow[..., 1],None,0,255,cv2.NORM_MINMAX)\n",
    "        # Add into list \n",
    "        flows.append(flow)\n",
    "        \n",
    "    # Padding the last frame as empty array\n",
    "    flows.append(np.zeros((224,224,2)))\n",
    "      \n",
    "    return np.array(flows, dtype=np.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-07T03:07:27.322865Z",
     "start_time": "2020-04-07T03:07:27.315496Z"
    }
   },
   "outputs": [],
   "source": [
    "def Video2Npy(file_path, resize=(224,224)):\n",
    "    \"\"\"Load video and tansfer it into .npy format\n",
    "    Args:\n",
    "        file_path: the path of video file\n",
    "        resize: the target resolution of output video\n",
    "    Returns:\n",
    "        frames: gray-scale video\n",
    "        flows: magnitude video of optical flows \n",
    "    \"\"\"\n",
    "    # Load video\n",
    "    cap = cv2.VideoCapture(file_path)\n",
    "    # Get number of frames\n",
    "    len_frames = int(cap.get(7))\n",
    "    # Extract frames from video\n",
    "    try:\n",
    "        frames = []\n",
    "        for i in range(len_frames-1):\n",
    "            _, frame = cap.read()\n",
    "            frame = cv2.resize(frame,resize, interpolation=cv2.INTER_AREA)\n",
    "            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n",
    "            frame = np.reshape(frame, (224,224,3))\n",
    "            frames.append(frame)   \n",
    "    except:\n",
    "        print(\"Error: \", file_path, len_frames,i)\n",
    "    finally:\n",
    "        frames = np.array(frames)\n",
    "        cap.release()\n",
    "            \n",
    "    # Get the optical flow of video\n",
    "    flows = getOpticalFlow(frames)\n",
    "    \n",
    "    result = np.zeros((len(flows),224,224,5))\n",
    "    result[...,:3] = frames\n",
    "    result[...,3:] = flows\n",
    "    \n",
    "    return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-07T03:07:27.804106Z",
     "start_time": "2020-04-07T03:07:27.798453Z"
    }
   },
   "outputs": [],
   "source": [
    "def Save2Npy(file_dir, save_dir):\n",
    "    \"\"\"Transfer all the videos and save them into specified directory\n",
    "    Args:\n",
    "        file_dir: source folder of target videos\n",
    "        save_dir: destination folder of output .npy files\n",
    "    \"\"\"\n",
    "    if not os.path.exists(save_dir):\n",
    "        os.makedirs(save_dir)\n",
    "    # List the files\n",
    "    videos = os.listdir(file_dir)\n",
    "    for v in tqdm(videos):\n",
    "        # Split video name\n",
    "        video_name = v.split('.')[0]\n",
    "        # Get src \n",
    "        video_path = os.path.join(file_dir, v)\n",
    "        # Get dest \n",
    "        save_path = os.path.join(save_dir, video_name+'.npy') \n",
    "        # Load and preprocess video\n",
    "        data = Video2Npy(file_path=video_path, resize=(224,224))\n",
    "        data = np.uint8(data)\n",
    "        # Save as .npy file\n",
    "        np.save(save_path, data)\n",
    "    \n",
    "    return None"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TODO Here\n",
    "- replace the source_path to the path of original dataset\n",
    "- replace the target_path to where you want to save transformed data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2020-04-07T03:09:54.008288Z",
     "start_time": "2020-04-07T03:07:54.971692Z"
    }
   },
   "outputs": [],
   "source": [
    "source_path = '...'\n",
    "target_path = '...'\n",
    "\n",
    "for f1 in ['train', 'val']:\n",
    "    for f2 in ['Fight', 'NonFight']:\n",
    "        path1 = os.path.join(source_path, f1, f2)\n",
    "        path2 = os.path.join(target_path, f1, f2)\n",
    "        Save2Npy(file_dir=path1, save_dir=path2)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
